<?php
class common_region_city_concept extends system_concept_abstract {
	
	public function init() {	
		$this->setModel('common_region_city_model', 'city');
		$this->setJoinLeftModel('common_region_model', 'province.id = city.province_id', 'province');
		$this->setModelCols('city', array('id', 'name', 'ename', 'province_id', 'zipcode'));
		$this->setModelCols('province', array('name' => 'province_name'));
	}

	public function save($row) {
		if($row->getName() == null) {
			throw new common_exception("Name can not be empty.");
		}
		if($row->getProvinceId() == null) {
			throw new common_exception("Province can not be empty.");
		}
		if($row->getId()) {
			if($this->fetch(array('city.id != ?' => $row->getId(), 'city.province_id = ?' => $row->getProvinceId(), 'city.name = ?' => $row->getName()))) {
				throw new common_exception("Name ({$row->getName()}) is already existing.");
			}
			$this->getModel('city')->update($row->getModelData('city'), array('id=?' => $row->getId()));
			return $row;
		}
		if($this->fetch(array('city.province_id = ?' => $row->getProvinceId(), 'city.name = ?' => $row->getName()))) {
			throw new common_exception("Name ({$row->getName()}) is already existing.");
		}
		$id = $this->getModel('city')->insert($row->getModelData('city'));
		$row->setId($id);
		return $row;
	}
	
	public function delete($row) {
		$concept = new common_region_zone_concept();
		if($concept->fetchCount(array('zone.city_id = ?' => $row->getId()))) {
			throw new common_exception("This City can not be deleted,Please delete all zones in the City first.");
		}
		parent::delete($row);
	}
	
	protected $_province = null;
	public function getProvince($row) {
		if($this->_province === null || $this->_province->getId() != $row->getProvinceId()) {
			$concept = new common_region_concept();
			$this->_province = $concept->fetch(array('region.id = ?' => $row->getProvinceId()));
		}
		return $this->_province;
	}

}